package cn.edu.ecust.market.controller;

import cn.edu.ecust.market.entity.Product;
import cn.edu.ecust.market.result.Result;
import cn.edu.ecust.market.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 查询商品
     */
    @GetMapping("/product/{productId}")
    public Result<Product> getProduct(@PathVariable Long productId) {
        return Result.success(productService.getById(productId));
    }

    /**
     * 查询商品列表
     */
    @GetMapping("/product")
    public Result<List<Product>> getProductList() {
        return Result.success(productService.list());
    }

    /**
     * 更新商品
     * 用于设置库存或设置秒杀时间
     */
    @PostMapping("/product/{productId}")
    public Result<Void> setInventory(@PathVariable Long productId, @RequestBody Map<String,String> params) {
        // 获取参数
        String inventory = params.get("inventory");
        String time = params.get("time");
        // 设置属性
        Product product = new Product();
        product.setId(productId);
        if(inventory != null) {
            product.setInventory(Integer.parseInt(inventory));
        }
        if(time != null) {
            product.setTime(LocalDateTime.parse(time.substring(0,23)));
        }
        // 更新
        productService.updateById(product);
        return Result.success();
    }

}
